package cn.shop.core.controller;

import cn.shop.core.bean.GoodsInfo;
import cn.shop.core.bean.ImgUrl;
import cn.shop.core.service.GoodsService;
import cn.shop.core.service.StaticPageService;
import cn.shop.utils.BaseController;
import cn.shop.utils.Common;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2016/8/26.
 * 商品管理控制器
 */
@Controller
@RequestMapping("/goods")
public class GoodsController extends BaseController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StaticPageService pageService;

    @RequestMapping("load.do")
    public String loadAdd(){
        return "goodsinfo/goodsinfo_add";
    }
    @RequestMapping("upload.do")
    public @ResponseBody
    ImgUrl uploadImag(@RequestParam(required = false) MultipartFile shopimg){
        try {

            // 图片名称生成策略
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String format = df.format(new Date());
            System.out.println(format);
            Random r = new Random();
            for (int i = 0; i < 3; i++) {
                format += r.nextInt(100);
            }

            // 保存数据库路径
            String path = "upload/" + format + ".jpg";

            // 另外一台服务器地址
            String url = Common.IMG_SERVER_URL + path;

            // 实例化jersey
            Client client = new Client();

            // 设置请求路径
            WebResource resource = client.resource(url);

            resource.put(String.class, shopimg.getBytes());

            ImgUrl iu = new ImgUrl();
            iu.setPath(path);
            iu.setUrl(url);

            return iu;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping("uploadfile.do")
    public void uploadfile(@RequestParam(required = false) MultipartFile upload, HttpServletResponse response, HttpServletRequest request) {

        try {
            // 图片名称生成策略
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String format = df.format(new Date());
            System.out.println(format);
            Random r = new Random();
            for (int i = 0; i < 3; i++) {
                format += r.nextInt(100);
            }

            // 保存数据库路径
            String path = "upload/" + format + ".jpg";

            // 另外一台服务器地址
            String url = Common.IMG_SERVER_URL + path;

            // 实例化jersey
            Client client = new Client();

            // 设置请求路径
            WebResource resource = client.resource(url);

            resource.put(String.class, upload.getBytes());

            //响应
            PrintWriter out = response.getWriter();
            //获取路径
            //String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();

            String callback = request.getParameter("CKEditorFuncNum");

            out.print("<script>window.parent.CKEDITOR.tools.callFunction("+callback+",'"+url+"') </script>");



            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param
     * @param model
     * @return
     */
    @RequestMapping("add.do")
    public String add(GoodsInfo goodsinfo, Model model) {

        String info = "操作失败";
        try {

            if (goodsinfo != null) {
                goodsinfo.setGoodsState(Common.GOODS_STATE_INIT);
            }
            goodsService.add(goodsinfo);
            info = "操作成功";
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("info", info);

        return "goodsinfo/goodsinfo_add";
    }

    /**
     * 查询商品信息
     * @param
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    public String list(GoodsInfo info,Model model,HttpServletRequest request){

        if(info!=null){
            this.initPage(request);
            info.setStart(this.getPageNo());//起始记录数
            info.setLength(PAGE_NUM_BIG);//每页显示记录数
        }

        List<Map> list = goodsService.getGoodsList(info);

        model.addAttribute("list", list);
        //总记录数
        model.addAttribute("total", goodsService.getGoodsCount(info));

        return "goodsinfo/goodsinfo_list";
    }

    /**
     * 查看商品信息
     * @param info
     * @param model
     * @return
     */
    @RequestMapping("goodsinfo.do")
    public String getInfo(GoodsInfo info,Model model){

        Map map = goodsService.getGoods(info);

        model.addAttribute("goods", map);

        return "goodsinfo/goodsinfo_show";
    }

    /**
     * 查看商品信息
     * @param info
     * @param model
     * @return
     */
    @RequestMapping("loadupdate.do")
    public String loadupdate(GoodsInfo info,Model model){

        Map map = goodsService.getGoods(info);

        model.addAttribute("goods", map);

        return "goodsinfo/goodsinfo_update";
    }

    /**
     *
     * @param
     * @param model
     * @return
     */
    @RequestMapping("update.do")
    public String updates(GoodsInfo goodsinfo, Model model,HttpServletRequest request) {

        String info = "操作失败";
        try {

		/*	if (goodsinfo != null) {
				goodsinfo.setGoodsState(Common.GOODS_STATE_YES);
			}*/
            goodsService.updateGoods(goodsinfo);
            info = "操作成功";
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("info", info);

        return list(goodsinfo,model,request);
    }


    /**
     *
     * @param
     * @param model
     * @return
     */
    @RequestMapping("delete.do")
    public String delete(GoodsInfo goodsinfo, Model model,HttpServletRequest request) {

        String info = "下架失败";
        try {

            if (goodsinfo != null) {
                goodsinfo.setGoodsState(Common.GOODS_STATE_NO);
            }
            goodsService.updateGoods(goodsinfo);
            info = "下架成功";
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("info", info);
        goodsinfo.setGoodsState(null);

        return list(goodsinfo,model,request);
    }

    @RequestMapping("upgoods.do")
    public String upGoods(GoodsInfo goodsinfo, Model model,HttpServletRequest request){

        String info = "上架失败";
        try {

            if (goodsinfo != null) {
                goodsinfo.setGoodsState(Common.GOODS_STATE_YES);
            }
            goodsService.updateGoods(goodsinfo);
            info = "上架成功";


            Map map = goodsService.getGoods(goodsinfo);
            if(map!=null){

                map.put("imgUrl", Common.IMG_SERVER_URL);
            }

            pageService.outStaticPage(map, goodsinfo.getGoodsId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("info", info);
        goodsinfo.setGoodsState(null);

        return list(goodsinfo,model,request);
    }

}
